package com.bang.concurrency.example.singleton;

import com.bang.concurrency.annotations.Recommend;
import com.bang.concurrency.annotations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Auther: Bang
 * @Date: 2019/9/30 21:16
 * @Description: 单例模式 饿汉模式 使用枚举实现单例
 */
@ThreadSafe
@Slf4j
@Recommend
public class SingletonExample6 {

    // 私有化构造方法
    private SingletonExample6() {
    }


    // 静态的工厂方法
    public static SingletonExample6 getInstance() {
        return Singleton.INSTANCE.getInstance();
    }


    private enum Singleton {
        INSTANCE;
        private SingletonExample6 singleton;

        // JVM保证这个方法绝对只调用一次 私有的
        Singleton() {
            singleton = new SingletonExample6();
        }

        public SingletonExample6 getInstance() {
            return singleton;
        }
    }

    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        Set<SingletonExample6> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 500; i++) {
            service.execute(() -> {
                SingletonExample6 instance = SingletonExample6.getInstance();
                set.add(instance);
            });
        }
        service.shutdown();
        System.err.println(set.size());
    }


}
